package com.runrun.config;

import com.runrun.pojo.Configuration;
import com.runrun.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLSqlMapperBuild {
    private Configuration configuration;

    public XMLSqlMapperBuild(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseSqlMapper(InputStream inputStream) throws DocumentException {
        //获取UserMapper.xml中的内容
        Document document = new SAXReader().read(inputStream);
        //获取根节点
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> selectList = rootElement.selectNodes("//select");
        MapperDataParse(selectList, namespace);
        List<Element> insertList = rootElement.selectNodes("//insert");
        MapperDataParse(insertList, namespace);
        List<Element> updateList = rootElement.selectNodes("//update");
        MapperDataParse(updateList, namespace);
        List<Element> deleteList = rootElement.selectNodes("//delete");
        MapperDataParse(deleteList,namespace);
    }

    //考虑到无论是select,insert,update还是delete解析步骤一样，故，将解析步骤提取
    private void MapperDataParse(List<Element> elementList, String namespace) {
        // todo 创建对象在循环里合循环外区别
        for (Element element : elementList) {
            MappedStatement mappedStatement = new MappedStatement();
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String SqlText = element.getTextTrim();
            String statementId = namespace + "." + id;
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(SqlText);
            mappedStatement.setId(id);
            mappedStatement.setParamterType(paramterType);
            configuration.getMappedStatementMap().put(statementId, mappedStatement);

        }
    }
}
